﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Common.Logging;

namespace KeepAliveHttp.Http
{
    public class SessionManager
    {
        private static List<WebClientConnection> _connections = new List<WebClientConnection>();
        private static readonly ILog logger = LogManager.GetLogger(typeof(SessionManager));
        private static object syncObj = new object();
        public static void AddConnection(WebClientConnection connection)
        {
            lock (syncObj)
            {
                _connections.Add(connection);
            }
        }
        public static void RemoveConnection(WebClientConnection connection)
        {
            lock (syncObj)
            {
                _connections.Remove(connection);
            }
        }
        public static WebClientConnection GetConnection(string sessionId)
        {
            lock (syncObj)
            {
                return _connections.FirstOrDefault(c => c.SessionId == sessionId);
            }
        }
        public static void SendAll(string message)
        {
            lock (syncObj)
            {
                foreach (var connection in _connections)
                {
                    connection.Send(message);
                }
            }
        }
        public static void Clean()
        {
            // 清理5分钟前的过时连接或者已经完成的连接
            lock (syncObj)
            {
                var now = DateTime.Now;
                var connections = _connections.Where(c => c == null || c.CreateTime.AddMinutes(5) < now || c.IsCompleted).ToList();
                foreach (var connection in connections)
                {
                    _connections.Remove(connection);
                }
                logger.InfoFormat("清理连接数：{0}", connections.Count);
            }
        }
    }
}